package cn.e3mall.cart.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e3mall.cart.service.CartService;
import cn.e3mall.common.util.CookieUtils;
import cn.e3mall.common.util.E3Result;
import cn.e3mall.common.util.JsonUtils;
import cn.e3mall.pojo.TbItem;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.service.ItemService;

/**
 * 购物车处理controller
 * @author shanqingyun
 *
 */
@Controller
public class CartController {
	@Autowired
	private ItemService itemService;
	@Value("${COOKIE_CART_EXPIRE}")
	private Integer COOKIE_CART_EXPIRE;
	@Autowired
	private CartService cartService;
	
	@RequestMapping("/cart/add/{itemId}")
	public String  addCart(@PathVariable Long itemId,@RequestParam(defaultValue="1") Integer num,
			HttpServletRequest request,HttpServletResponse response){
		//判断用户是否为登录状态
		TbUser user=(TbUser) request.getAttribute("user");
		//如果是登录状态,将购物车写入redis
		if(user!=null){
			//保存到服务端
			cartService.addCart(user.getId(), itemId, num);
			//返回逻辑视图
			return "cartSuccess";
		}
		//未登录写入cookie
		//从cookie中取购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		boolean flag=false;
		//判断商品在商品列表中是否存在
		for (TbItem tbItem : cartList) {
			if(tbItem.getId()==itemId.longValue()){
				//如果存在数量相加
				tbItem.setNum(tbItem.getNum()+num);
				flag=true;
				//跳出循环
				break;
			}
		}
		//如果不存在从根据id数据库查询商品信息,得到一个tbitem 对象
		if(!flag){
			//根据商品ID查询商品信息
			TbItem tbItem= itemService.getItemById(itemId);
			//设置商品数量
			tbItem.setNum(num);
			//取图片
			String image=tbItem.getImage();
			if(StringUtils.isNotBlank(image)){
				tbItem.setImage(image.split(",")[0]);
			}
			//把商品添加到商品列表
			cartList.add(tbItem);
		}
		//写入cookie
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList), COOKIE_CART_EXPIRE, true);
		//返回添加成功页面
		return "cartSuccess";
	}
	/**
	 * 从cookie中取购物车列表
	 * @param request
	 * @return
	 */
	private List<TbItem> getCartListFromCookie(HttpServletRequest request){
		String json = CookieUtils.getCookieValue(request, "cart", true);
		if(StringUtils.isBlank(json)){
			return new ArrayList<TbItem>();
		}
		//把json转换成商品列表
		return JsonUtils.jsonToList(json, TbItem.class);
	}
	
	/**
	 * 展示购物车列表
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/cart/cart")
	public String showCartList(HttpServletRequest request,HttpServletResponse response){
		//从cookie中取购物车列表
		List<TbItem> cartList = getCartListFromCookie(request);
		//判断用户是否为登录状态
		TbUser user=(TbUser) request.getAttribute("user");
		//如果是登录状态,从cookie中取购物车列表
		//不为空则将cookie中的商品与服务端的购物车合并
		if(user!=null){
			cartService.mergeCart(user.getId(), cartList);
			//把cookie中的购物车删除
			CookieUtils.deleteCookie(request, response, "cart");
			//从服务端取购物车列表,
			cartList = cartService.getCartList(user.getId());
		}
		//未登录状态
		//把列表传递给页面
		request.setAttribute("cartList", cartList);
		//返回逻辑视图
		return "cart";
	}
	/**
	 * 更新购物车
	 * @param itemId
	 * @param num
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/cart/update/num/{itemId}/{num}")
	@ResponseBody
	public E3Result updateCartNum(@PathVariable Long itemId,@PathVariable Integer num,
			HttpServletRequest request,HttpServletResponse response){
		//判断用户是否为登录状态
		TbUser user = (TbUser) request.getAttribute("user");
		//如果用户登录了更新服务器端的购物车
		if(user!=null){
			return cartService.updateCartNum(user.getId(), itemId, num);
		}
		
		//未登录
		//取购物列表
		List<TbItem> cartList = getCartListFromCookie(request);
		//遍历列表找到对应的商品
		for (TbItem tbItem : cartList) {
			if(tbItem.getId()==itemId.longValue()){
				//更新数量
				tbItem.setNum(num);
				break;
			}
		}
		//把购物车列表写回cookie
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList),COOKIE_CART_EXPIRE, true);
		//返回成功
		return E3Result.ok();
		
	}
	/**
	 * 删除购物车商品
	 * @param itemId
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/cart/delete/{itemId}")
	public String deleteCartItem(@PathVariable Long itemId,HttpServletRequest request,HttpServletResponse response){
		//判断用户是否为登录状态
			TbUser user = (TbUser) request.getAttribute("user");
			//如果用户登录了更新服务器端的购物车
			if(user!=null){
				cartService.deleteCartItem(user.getId(), itemId);
				return "redirect:/cart/cart.html";
			}
			
		//从cookie中找到要删除的商品
		List<TbItem> cartList = getCartListFromCookie(request);
		//删除商品
		for (TbItem tbItem : cartList) {
			if(tbItem.getId()==itemId.longValue()){
				cartList.remove(tbItem);
				break;
			}
		}
		//把购物车写回cookie中
		CookieUtils.setCookie(request, response, "cart", JsonUtils.objectToJson(cartList),COOKIE_CART_EXPIRE, true);
		//跳转
		return "redirect:/cart/cart.html";
		
	}
 	
}
